# -*- encoding: utf-8 -*-
##############################################################################
#
#    OpenERP, Open Source Management Solution	
#    Copyright (C) 2004-2009 Tiny SPRL (<http://tiny.be>). All Rights Reserved
#    $Id$
#
#    This program is free software: you can redistribute it and/or modify
#    it under the terms of the GNU General Public License as published by
#    the Free Software Foundation, either version 3 of the License, or
#    (at your option) any later version.
#
#    This program is distributed in the hope that it will be useful,
#    but WITHOUT ANY WARRANTY; without even the implied warranty of
#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#    GNU General Public License for more details.
#
#    You should have received a copy of the GNU General Public License
#    along with this program.  If not, see <http://www.gnu.org/licenses/>.
#
##############################################################################

from osv import fields,osv
from osv.orm import except_orm
import tools


class product_product(osv.osv):
    _name = "product.product"
    _description = "Product"
    _inherit="product.product"
    
    _columns = {
                'brand_ids':fields.one2many('kdvn.product.brandname','product_id','Brands')
                }
product_product()
class product_template(osv.osv):
    _name = "product.template"
    _description = "Product Template"
    _inherit="product.template"

    _columns = {
        'type': fields.selection([('product','Stockable Product'),('consu', 'Consumable'),('service','Service')], 'Product Type', required=False, help="Will change the way procurements are processed. Consumables are stockable products with infinite stock, or for use when you have no stock management in the system."),
        'supply_method': fields.selection([('produce','Produce'),('buy','Buy')], 'Supply method', required=False, help="Produce will generate production order or tasks, according to the product type. Purchase will trigger purchase orders when requested."),
        'procure_method': fields.selection([('make_to_stock','Make to Stock'),('make_to_order','Make to Order')], 'Procure Method', required=False, help="'Make to Stock': When needed, take from the stock or wait until re-supplying. 'Make to Order': When needed, purchase or produce for the procurement request."),
        'standard_price': fields.float('Cost Price', required=False, digits=(16,2), help="The cost of the product for accounting stock valuation. It can serves as a base price for supplier price."),
        'cost_method': fields.selection([('standard','Standard Price'), ('average','Average Price')], 'Costing Method', required=False,
            help="Standard Price: the cost price is fixed and recomputed periodically (usually at the end of the year), Average Price: the cost price is recomputed at each reception of products."),
        'uom_po_id': fields.many2one('product.uom', 'Purchase UoM', required=False, help="Default Unit of Measure used for purchase orders. It must in the same category than the default unit of measure."),
        'mes_type': fields.selection((('fixed', 'Fixed'), ('variable', 'Variable')), 'Measure Type', required=False)
    }
    def _check_uom(self, cursor, user, ids):
        return True

    def _check_uos(self, cursor, user, ids):
        return True

    _constraints = [
        (_check_uos, 'Error: UOS must be in a different category than the UOM', ['uos_id']),
        (_check_uom, 'Error: The default UOM and the purchase UOM must be in the same category.', ['uom_id']),
    ]

product_template()

class kdvn_brand_name(osv.osv):
    _name = 'kdvn.brand.name'
    _description = 'KDVN Brand name'
    
    def search(self, cr, user, args, offset=0, limit=None, order=None,  context=None, count=False):
        if context:
            if 'pr_id' in context.keys():
                cr.execute("select \
                                brandname_id\
                            from \
                                kdvn_product_brandname pp\
                            where\
                                product_id=%d" % context['pr_id'])
                res = cr.fetchall()
                res1=[]
                for tmp in res:
                    res1.append(tmp[0])
                var_filter=res1
                if res1:
                    args.append(('id','in',var_filter))
            #raise osv.except_osv(_('Invalid action !'),_('Cannot delete Request(s) which are in (%s) State1!' %args))
           # args.append
        return super(kdvn_brand_name,self).search(cr, user, args, offset, limit, order,context, count)
    
    _columns={
              'code':fields.char('Code',size=10,required=True,select=1),
              'name':fields.char('Name',size=50,required=True,select=1),
              'product_ids':fields.one2many('kdvn.product.brandname','brandname_id','Products')
             }
    _sql_constraints = [('code_unique_brandname', 'unique (name)', 'KDVN Error: Brand name must be unique !')] 
kdvn_brand_name()

class kdvn_product_brandname(osv.osv):
    _name = 'kdvn.product.brandname'
    _description = 'KDVN Product and Brand name'
    
    _order='default_brand desc'
    _columns={
              'brandname_id':fields.many2one('kdvn.brand.name','Brand Name',required=True),
              'product_id':fields.many2one('product.product','Product'),
              'default_brand':fields.boolean('Default')
             }
    _sql_constraints = [('code_unique_brand_name', 'unique (partner_id)', 'KDVN Error: Brand name must be unique !')] 
    
    def create(self,cr, uid, vals, context=None):
        new_id = False
        new_id=osv.osv.create(self,cr, uid, vals, context)
        if vals['default_brand'] and vals['product_id'] and new_id:
            cr.execute('Update kdvn_brand_name set \
                                default_brand=False\
                            where product_id=%s and id<>%s' % (vals['product_id'],new_id))
        return new_id
    
    def write(self, cr, uid, ids, vals, context=None):
        osv.osv.write(self, cr, uid, ids,vals,context=context)
        if vals['default_brand']:
            cr.execute('Update kdvn_brand_name set \
                                default_brand=False\
                            where product_id=(Select product_id from kdvn_brand_name where id=%s) and id<>%s' % (ids[0],ids[0]))
        return True
kdvn_product_brandname()